package com.kadron.common;

import java.io.Serializable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.jboss.seam.Component;

public class KHibernate implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7924923368393629904L;

	static protected Log log = LogFactory.getLog(KHibernate.class);
	
	static protected SessionFactory sessionFactory;

	static public Session getSeamSession() {
		return (Session) Component.getInstance("ksession");
	}
	
	static public SessionFactory getSessionFactory() throws Exception {
		if (sessionFactory == null) {
			Configuration cfg = new AnnotationConfiguration().configure();
			sessionFactory = buildFactory(cfg);
		}
		return sessionFactory;
	}

	static protected SessionFactory buildFactory(Configuration cfg)
			throws Exception {
		try {
			sessionFactory = cfg.buildSessionFactory();
		} catch (Exception ex) {
			closeFactory(sessionFactory);
			sessionFactory = null;
			throw ex;
		}
		return sessionFactory;
	}

	static public void closeFactory(SessionFactory factory) {
		if (factory != null) {
			factory.close();
			factory = null;
		}
	}

	static public void closeFactory() {
		closeFactory(sessionFactory);
	}

	static public boolean isSessionOpen() {
		return sessionFactory != null;
	}

	static public Session getSession()
			throws HibernateException, Exception {
		return getSessionFactory().openSession();
	}

	public static void initSessionFactory() {
		try {
			sessionFactory = getSessionFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	static public void closeSession(org.hibernate.Session session) {
		try {
			if (session != null && session.isOpen()) {
				session.close();	
				session = null;
			}
		} catch (Exception e) {
			log.error(" -------------- Exception na close session -------------- ");
		}
	}
	
	static public void rollback(org.hibernate.Session hsession) {
		try {
			if (hsession != null) {
				if (hsession.getTransaction().isActive()) {
					hsession.getTransaction().rollback();				
				}
			}			
		} catch (Exception e) {
			log.error(" -------------- Exception na rollback trasakcije -------------- ");
		}
	}
	
}
